package org.shaitu.wakeremote4j;

import java.io.File;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

import org.shaitu.wakeremote4j.util.FileUtil;
import org.shaitu.wakeremote4j.util.StringProcessible;

/**
 * host persistence access
 * 
 * @author whx
 */
public class HostDAO {

	/**
	 * host map
	 */
	private static Map<String,HostBean> hostMap = new HashMap<String,HostBean>();

	static {
		loadHosts();
	}

	public static Collection<HostBean> getHosts() {
		return hostMap.values();
	}
	
	public static Vector<String> getHostNames() {
		Vector<String> names = new Vector();
		Collection<HostBean> hosts = hostMap.values();
		for(HostBean host:hosts){
			names.add(host.getName());
		}
		Collections.sort(names);
        names.add(0, "");
		return names;
	}

	public static HostBean getHost(String name) {
		return hostMap.get(name);
	}

	public static boolean createHost(HostBean bean) {
		hostMap.put(bean.getName(), bean);
		storeHosts();
		return true;
	}

	public static boolean deleteHost(String name) {
		hostMap.remove(name);
		storeHosts();
		return true;
	}

	public static boolean clearAllHost() {
		hostMap.clear();
		storeHosts();
		return true;
	}
	
	/**
	 * load hosts from file to map
	 */
	private static void loadHosts(){
		File hostsFile = new File(AppContext.HOSTS_FILE);
		if(!hostsFile.exists()){
			return;
		}
		StringProcessible processor = new StringProcessible(){
			public Object process(String content){
				if(!content.startsWith("#")){
					HostBean bean = HostBean.parseBean(content);
					hostMap.put(bean.getName(), bean);
				}
				return null;
			}
		};
		FileUtil.lineIterator(new File(AppContext.HOSTS_FILE), processor);
	}

	/**
	 * store hosts from map to file
	 */
	private static void storeHosts() {
		FileUtil.storeList(new File(AppContext.HOSTS_FILE), hostMap.values());
	}

}
